package slap.server;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.slf4j.LoggerFactory;

import slap.Slap;
import slap.concurrent.Invoker.Invocation;
import slap.exception.NotFoundException;
import slap.http.Request;
import slap.http.Response;
import slap.mvc.ActionInvoker;
import slap.mvc.scope.Session;
import slap.util.Perf4j;

public class HttpRequestInvokation extends Invocation {
	private final ChannelHandlerContext ctx;
    private final Request request;
    private final Response response;
    private final HttpRequest nettyRequest;
    private final MessageEvent event;

    public HttpRequestInvokation(Request request, Response response, ChannelHandlerContext ctx, HttpRequest nettyRequest, MessageEvent e) {
        this.ctx = ctx;
        this.request = request;
        this.response = response;
        this.nettyRequest = nettyRequest;
        this.event = e;
    }

    @Override
    public boolean init() {
        Request.setCurrent(request);
        Response.current.set(response);
        Session.setCurrent(request.sessionId);
        super.init();
        return true;
    }

    @Override
    public void run() {
        try {
            super.run();
        } catch (Exception e) {
        	//TODO ser500
        }
    }

    @Override
    public void execute() throws Exception {
        if (!ctx.getChannel().isConnected()) {
            try {
                ctx.getChannel().close();
            } catch (Throwable e) {
                // Ignore
            }
            return;
        }
        ActionInvoker.invoke(request, response);
    }

    @Override
    public void onSuccess() throws Exception {
        super.onSuccess();
        FrameworkHandler.copyResponse(ctx, request, response, nettyRequest);
    }
}
